package 网络编程.客户端与服务器的请求与响应.UDP数据报.客户端;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    //构造初始化
    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();//不写参数随机分配
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {

        System.out.println("客户端启动");
        Scanner sc = new Scanner(System.in);
        while(true){

            System.out.println("请求输入要发送的请求");
            //1、从控制台读取字符串
            String request = sc.next();

            //2、把字符串发送给服务器
            //构造请求数据报的时候，不光要有数据，还要有“目标”
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);

            //3、从服务器读取到响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[2048],2048);
            socket.receive(responsePacket);

            //4、把相应打印到控制台
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);

        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9099);
        client.start();
    }
}
